package com.lu.service;

import com.lu.bean.AppException;
import com.lu.constant.ErrorEnum;
import com.lu.constant.TypeEnum;
import com.lu.dao.mapper.WgBranchRecordMapper;
import com.lu.dao.mapper.WgSubmitRecordMapper;
import com.lu.dao.po.WgBranchRecord;
import com.lu.dao.po.WgSubmitRecord;
import com.lu.dao.po.WgSubmitRecordExample;
import com.lu.util.CreateIdUtil;
import com.lu.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.util.Arrays;
import java.util.List;

/**
 * @author luke
 * @className SubmitService
 * @description
 * @date 2021/07/13 11:54
 */
@Slf4j
@Service
public class SubmitService {

    @Value("${config.imgPath}")
    private String imgPath;

    @Value("${config.preUrl}")
    private String preUrl;

    @Resource
    private WgSubmitRecordMapper wgSubmitRecordMapper;

    @Resource
    private WgBranchRecordMapper wgBranchRecordMapper;

    public String uploadImg(MultipartFile img) throws AppException {

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        String imgUrl = null;
        try {
            //文件信息getContentType【image/jpeg】,
            //文件信息getOriginalFilename【七国.png】,文件的后缀，需要进一步讨论下，怎么结局。其实不用后缀也可以。
            String fileName = CreateIdUtil.createId("img_");
            File file = new File(imgPath + fileName);
            file.createNewFile();
            bis = new BufferedInputStream(img.getInputStream());
            bos = new BufferedOutputStream(new FileOutputStream(file));

            byte[] b = new byte[1024];
            while(bis.read(b) != -1) {
                bos.write(b);
            }
            bos.flush();
            bos.close();
            bis.close();
            imgUrl = preUrl + fileName;
        } catch (IOException e) {
            log.error("img upload error,",e);
            throw new AppException(ErrorEnum.IMG_UPLOAD_ERROR);
        }finally {
            try {
                if(bis != null) {
                    bis.close();
                }
                if(bos != null) {
                    bos.close();
                }
            } catch (IOException e) {
                log.error("IoException occur,",e);
            }
        }
        return imgUrl;
    }

    public void submit(WgSubmitRecord req) throws AppException {

        WgBranchRecord record = wgBranchRecordMapper.selectByBranchId(req.getBranchId());
        if(record == null) {
            log.error("branch id[{}] not exist",req.getBranchId());
            throw new AppException(ErrorEnum.BRANCH_NOT_EXIST);
        }

        String[] playerArray = record.getParticipant().split(",");
        List<String> playerList = Arrays.asList(playerArray);
        int index = playerList.indexOf(req.getOpenId());
        if(index == -1) {
            throw new AppException(ErrorEnum.PLAYER_ILLEGAL);
        }

        WgSubmitRecordExample example1 = new WgSubmitRecordExample();
        example1.createCriteria().andNextOpenIdEqualTo(req.getOpenId()).andBranchIdEqualTo(req.getBranchId());
        int count1 = wgSubmitRecordMapper.countByExample(example1);
        if(count1 < 1) {
            throw new AppException(ErrorEnum.PRE_PLAYER_EMPTY);
        }

        WgSubmitRecordExample example2 = new WgSubmitRecordExample();
        example2.createCriteria().andOpenIdEqualTo(req.getOpenId()).andBranchIdEqualTo(req.getBranchId());
        int count2 = wgSubmitRecordMapper.countByExample(example2);
        if(count2 > 0) {
            throw new AppException(ErrorEnum.SUBMIT_REPEAT);
        }

        String preOpenId = null;
        String nextOpenId = null;
        if(index > 0) {
            preOpenId = playerArray[index-1];
        }
        if(index < playerList.size()-1) {
            nextOpenId = playerArray[index+1];
        }

        WgSubmitRecord submitRecord = new WgSubmitRecord();
        submitRecord.setOpenId(req.getOpenId());
        submitRecord.setUserName(req.getUserName());
        submitRecord.setPreOpenId(preOpenId);
        submitRecord.setNextOpenId(nextOpenId);
        submitRecord.setGuessWord(req.getGuessWord());
        submitRecord.setPicture(req.getPicture());
        submitRecord.setType(req.getType());
        submitRecord.setGameId(record.getGameId());
        submitRecord.setBranchId(record.getBranchId());
        submitRecord.setOrderNum(index);
        submitRecord.setCreateTime(DateUtil.getNowTimeStr());
        wgSubmitRecordMapper.insert(submitRecord);
    }

}
